﻿using System.Windows;
using System.Windows.Controls;
namespace TciNewsReader_2014_04.Behaviours
{
    public static class ScrollingBehaviour
    {// keep the selected item visible
        #region ListBoxScrollingBehaviour (Attached DependencyProperty)
        public static readonly DependencyProperty ListBoxScrollingBehaviourProperty =
            DependencyProperty.RegisterAttached("ListBoxScrollingBehaviour", typeof(object), 
            typeof(ScrollingBehaviour), new PropertyMetadata(OnListBoxScrollingBehaviourChanged));
        public static void SetListBoxScrollingBehaviour(DependencyObject o, object value)
        {
            o.SetValue(ListBoxScrollingBehaviourProperty, value);
        }
        public static object GetListBoxScrollingBehaviour(DependencyObject o)
        {
            return (double)o.GetValue(ListBoxScrollingBehaviourProperty);
        }
        private static void OnListBoxScrollingBehaviourChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ListBox lb = d as ListBox;
            if (lb != null)
            {
                lb.SelectionChanged += (s, a) =>
                {
                    ListBox l = s as ListBox;
                    if (l != null)
                    {
                        l.ScrollIntoView(l.Items.CurrentItem);
                    }
                };
            }
        }
        #endregion
    }
}
